import Clipboard from 'clipboard'
import {
  vueInstance
} from '@/main'

// 根据数字获取大小写
export const digitUppercase = (n) => {
  var fraction = ['角', '分']
  var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  var unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  var head = n < 0 ? '欠' : ''
  n = Math.abs(n)
  var s = ''
  for (var i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
  }
  s = s || '整'
  n = Math.floor(n)
  // eslint-disable-next-line no-redeclare
  for (var i = 0; i < unit[0].length && n > 0; i++) {
    var p = ''
    for (var j = 0; j < unit[1].length && n > 0; j++) {
      p = digit[n % 10] + unit[1][j] + p
      n = Math.floor(n / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }
  return head + s.replace(/(零.)*零元/, '元')
    .replace(/(零.)+/g, '零')
    .replace(/^整$/, '零元整')
}
// 格式化日期
export const formatDate = (date, fmt) => {
  if (!date) return null
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

export const padLeftZero = (str) => {
  return ('00' + str).substr(str.length)
}

// 格式化金额
export const formatFuc = (num, floor = false) => {
  if (!num) {
    num = 0
  }
  let result = ''
  let numData = ''
  numData = num
  numData = Number(numData || 0).toFixed(3)
  const isMinus = numData < 0
  numData = numData.replace('-', '')
  const numAry = numData.split('.')
  let preNum = numAry[0]
  var lastNum = numAry[1]
  while (preNum.length > 3) {
    result = ',' + preNum.slice(-3) + result
    preNum = preNum.slice(0, preNum.length - 3)
  }
  if (preNum) {
    result = preNum + result
  }
  if (lastNum && !floor) {
    lastNum = lastNum.substring(0, 2)
    result = result + '.' + lastNum
  }
  return `${isMinus ? '-' : ''}${result}`
}

// 根据毫秒转时间
export const countGetHours = (time) => {
  let time1 = new Date(time).getHours()
  if (time1 < 10) {
    time1 = '0' + time1
  }
  let minutes = new Date(time).getMinutes()
  if (minutes < 10) {
    minutes = '0' + minutes
  }
  const times = time1 + ':' + minutes

  return times
}

// 获取剩余天数
export const newDateEnd = (diffDays) => {
  var dateTo = new Date()
  const format = formatDate(new Date(diffDays), 'yyyy/MM/dd 00:00:00')
  var dateFrom = new Date(format)
  var diff = dateFrom.valueOf() - dateTo.valueOf()
  diffDays = parseInt(diff / (1000 * 60 * 60 * 24)) + 1
  if (diffDays < 0 || diffDays === '' || diffDays === undefined) {
    return 0
  } else {
    return diffDays
  }
}

// 时间戳转年月日显示
export const timestampToTime = (timestamp) => {
  var date = new Date(timestamp)
  var Y = date.getFullYear() + '年'
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月'
  var D = date.getDate() + '日'
  return Y + M + D
}

// 去浮点
export const floatPoint = (value) => {
  if (!value) return 0
  return parseFloat((Number(value)).toFixed(10))
}

export const transferPercentString = (value, decimal = null) => {
  if (!value) return value
  let mulVal = floatPoint(value * 100)
  // 保留小数
  if (decimal !== null) {
    mulVal = Number(mulVal).toFixed(decimal)
  }
  return `${mulVal}%`
}

export const amountConversion = (value) => {
  return (value / 10000).toFixed(2)
}

// 百倍
export const mulOneHundred = (value) => {
  if (!value) return 0
  return floatPoint(value * 100)
}

// 千分显示，不保留小数
export const thousandSplitFloat = (value) => {
  if (!value) return 0
  const str = `${parseInt(value)}`
  return str.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,')
}

/**
 * @param Object 需要赋值的对象
 * @param Object 提供赋值数据的对象
 * @describe `返回对象的交集 对象的value 为 hasValueObj的值`
 */
export const objectAsignMin = (noValueObj = {}, hasValueObj = {}) => {
  Object.keys(noValueObj).forEach(key => {
    if (Object.prototype.hasOwnProperty.call(hasValueObj, key)) noValueObj[key] = hasValueObj[key]
  })
  return {
    ...noValueObj
  }
}

// 计算成交金额
export const bargainMoneyValue = (amount, feePerLakh) => {
  const interest = (amount / 100000) * feePerLakh
  // 年化利率=（利息1+剩余天数/360） / 票面金额
  // const annualRateValue = (interest / (amount * (newDateEnd(dueDate, currentDate) / 360)) * 100)
  // 成交金额=票面金额-利息
  // return Math.floor((amount-interest)* 100)/100
  return (amount - interest).toFixed(2)
}

export const copyFunc = (selector) => {
  var clipboard = new Clipboard(selector)
  clipboard.on('success', () => {
    vueInstance.$message({
      type: 'success',
      message: '复制成功'
    })
  })
  clipboard.on('error', () => {
    vueInstance.$message({
      type: 'warning',
      message: '复制失败'
    })
  })
}
// 实名认证用
export const idCardNumber = (tel) => {
  if (tel == null) {
    tel = '-'
  }
  tel = '' + tel
  var ary = tel.split('')
  if (tel.length === 18) {
    ary.splice(3, 11, '***********')
  } else if (tel.length === 15) {
    ary.splice(3, 8, '********')
  }
  return ary.join('')
}

export const getOSSFileName = (url) => {
  return decodeURI && decodeURI(url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('?')))
}
